import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { useSelector } from 'react-redux'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'

interface editableInputType {
  onClose?: () => void
  type: '' | 'name' | 'intro'
  onUpdate?: (value: string, type: string) => void
}

//为了让组件更加通用, 应该让组件只去处理用户输入的数据, 在需要的时候进行回传!!!
// 子组件回传数据给父组件, 子传父. 父组件向下传递一个函数, 通过函数进行获取子组件的数据

const EditInput = ({ onClose, type, onUpdate }: editableInputType) => {
  const { userProfile } = useSelector((state: RootState) => state.profile)
  //定义状态: 控制input textarea的值
  const [val, setVal] = useState(() => {
    return type === 'name' ? userProfile.name : userProfile.intro // return 初始值 组价渲染的时候才会加载一次
  })

  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)

  useEffect(() => {
    // 有就聚焦
    inputRef.current?.focus()
    textRef.current?.focus()
  }, [])

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        right={
          <span
            className="commit-btn"
            onClick={() => {
              // console.log('val', val, type)
              onUpdate?.(val, type)
              // onUpdate && onUpdate?.(val, type)
            }}
          >
            提交
          </span>
        }
        onBack={onClose}
      >
        编辑{type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type === 'name' ? '昵称' : '简介'}</h3>

        {type === 'name' ? (
          <div className="input-wrap">
            <Input
              value={val}
              onChange={(value) => {
                // console.log(value)
                setVal(value)
              }}
              placeholder="请输入"
              ref={inputRef}
            />
          </div>
        ) : (
          <TextArea
            maxLength={99}
            ref={textRef}
            value={val}
            onChange={(value) => {
              // console.log(value)
              setVal(value)
            }}
            className="textarea"
            placeholder="请输入简介"
            showCount
          ></TextArea>
        )}
      </div>
    </div>
  )
}

export default EditInput
